document.addEventListener('DOMContentLoaded', () => {
    const priorityOrder = { 高: 1, 中: 2, 低: 3 };

    let shoppingList = JSON.parse(localStorage.getItem('shoppingList')) || [
        { id: 1, name: '牛奶', member: 'xiangyang', purchased: false, quantity: 1, priority: '中', category: '日用品' },
        { id: 2, name: '面包', member: 'changpeng', purchased: true, quantity: 2, priority: '高', category: '水果' },
        { id: 3, name: '鸡蛋', member: 'jiangsiyu', purchased: false, quantity: 12, priority: '低', category: '蔬菜' }
    ];

    const itemsList = document.getElementById('itemsList');
    const newItemInput = document.getElementById('newItem');
    const quantityInput = document.getElementById('quantityInput');
    const prioritySelect = document.getElementById('prioritySelect');
    const categorySelect = document.getElementById('categorySelect');
    const addButton = document.getElementById('addButton');
    const memberSelect = document.getElementById('memberSelect');
    const teamMembers = document.querySelectorAll('.member');
    const categoryBtns = document.querySelectorAll('.category-btn');

    let currentMember = 'all';
    let currentCategory = 'all';

    function renderShoppingList(member = 'all', category = 'all') {
        itemsList.innerHTML = '';

        let filteredList = shoppingList;

        if (member !== 'all') {
            filteredList = filteredList.filter(item => item.member === member);
        }
        if (category !== 'all') {
            filteredList = filteredList.filter(item => item.category === category);
        }

        filteredList.sort((a, b) => priorityOrder[a.priority] - priorityOrder[b.priority]);

        filteredList.forEach(item => {
            const itemElement = document.createElement('div');
            itemElement.className = `item ${item.purchased ? 'purchased' : ''}`;

            itemElement.innerHTML = `
                <div class="item-name">${item.name}</div>
                <div>
                    <input 
                        type="number" min="1" value="${item.quantity}" 
                        data-id="${item.id}" 
                        class="quantity-input" style="width:60px;" 
                        title="数量"
                    />
                </div>
                <div>${item.priority}</div>
                <div>${item.category}</div>
                <div><span class="member-badge ${item.member}">${getMemberName(item.member)}</span></div>
                <div class="status ${item.purchased ? 'purchased' : 'pending'}" data-id="${item.id}" title="点击切换状态">
                    ${item.purchased ? '已购买' : '待购买'}
                </div>
                <div>
                    <button class="delete-btn" data-id="${item.id}" title="删除物品">删除</button>
                </div>
            `;

            itemsList.appendChild(itemElement);
        });

        document.querySelectorAll('.status').forEach(status => {
            status.addEventListener('click', togglePurchaseStatus);
        });

        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', deleteItem);
        });

        document.querySelectorAll('.quantity-input').forEach(input => {
            input.addEventListener('change', updateQuantity);
        });
    }

    function getMemberName(memberId) {
        const memberNames = {
            xiangyang: '向杨',
            changpeng: '常鹏',
            jiangsiyu: '蒋思宇',
            keyunhong: '柯昀宏',
            yezhiwei: '叶志威',
            yanghaomin: '杨昊旻'
        };
        return memberNames[memberId] || memberId;
    }

    function togglePurchaseStatus(e) {
        const itemId = parseInt(e.target.dataset.id);
        const itemIndex = shoppingList.findIndex(item => item.id === itemId);

        if (itemIndex !== -1) {
            shoppingList[itemIndex].purchased = !shoppingList[itemIndex].purchased;
            saveToLocalStorage();
            renderShoppingList(currentMember, currentCategory);
        }
    }

    function deleteItem(e) {
        const itemId = parseInt(e.target.dataset.id);
        shoppingList = shoppingList.filter(item => item.id !== itemId);
        saveToLocalStorage();
        renderShoppingList(currentMember, currentCategory);
    }

    function updateQuantity(e) {
        const itemId = parseInt(e.target.dataset.id);
        const newQuantity = parseInt(e.target.value);
        if (newQuantity < 1 || isNaN(newQuantity)) {
            e.target.value = 1;
            return;
        }
        const itemIndex = shoppingList.findIndex(item => item.id === itemId);
        if (itemIndex !== -1) {
            shoppingList[itemIndex].quantity = newQuantity;
            saveToLocalStorage();
        }
    }

    addButton.addEventListener('click', () => {
        const itemName = newItemInput.value.trim();
        const quantity = parseInt(quantityInput.value) || 1;
        const priority = prioritySelect.value;
        const category = categorySelect.value;
        const member = memberSelect.value;

        if (itemName) {
            const newItem = {
                id: Date.now(),
                name: itemName,
                member,
                purchased: false,
                quantity,
                priority,
                category
            };
            shoppingList.push(newItem);
            saveToLocalStorage();
            renderShoppingList(currentMember, currentCategory);

            newItemInput.value = '';
            quantityInput.value = 1;
            prioritySelect.value = '中';
            categorySelect.value = '其他';
        }
    });

    newItemInput.addEventListener('keypress', e => {
        if (e.key === 'Enter') {
            addButton.click();
        }
    });

    teamMembers.forEach(member => {
        member.addEventListener('click', () => {
            teamMembers.forEach(m => m.classList.remove('active'));
            member.classList.add('active');
            currentMember = member.dataset.member;
            renderShoppingList(currentMember, currentCategory);
        });
    });

    categoryBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            categoryBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            currentCategory = btn.dataset.category;
            renderShoppingList(currentMember, currentCategory);
        });
    });

    function saveToLocalStorage() {
        localStorage.setItem('shoppingList', JSON.stringify(shoppingList));
    }

    renderShoppingList(currentMember, currentCategory);
});
